package cc.eddic.practice.concurrency;


import cc.eddic.practice.concurrency.impl.LogParserWithExecuterImpl;
import cc.eddic.practice.concurrency.impl.LogParserWithFuturesImpl;
import cc.eddic.practice.concurrency.impl.gzipImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import lombok.val;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@SpringBootApplication
public class ConcurrencyLhApplication implements CommandLineRunner {
//    LogParserLhImpl logParserLh = new LogParserLhImpl();
    LogParserWithExecuterImpl logParserWithExecuter=new LogParserWithExecuterImpl();
    LogParserWithFuturesImpl logParserWithFuturesImpl=new LogParserWithFuturesImpl();
    gzipImpl gz=new gzipImpl();
    public static void main(String[] args) {
        SpringApplication.run(ConcurrencyLhApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        long start=System.currentTimeMillis();
        log.info("start");
        Map<String, List<LogItem>> map = gz.parse("C:\\Users\\李惠\\Desktop\\2023-04");
        if (log.isInfoEnabled()) {
            log.info("total log items : {}", map.values().stream().mapToLong(Collection::size).sum());
            log.info("valid log items : {}", map.values().stream().flatMap(Collection::stream).filter(LogItem::isValidRequest).count());
}
//   loop();
//        executer();
   log.info("{}",System.currentTimeMillis()-start);
    }
    private void executer(){
        ExecutorService executorService= Executors.newFixedThreadPool(16);
        CountDownLatch latch=new CountDownLatch(LOG_FILE_COUNT);
        for (int i=0;i<LOG_FILE_COUNT;i++){
            int finall=i;
            executorService.submit(()->dummyPrase1(finall,latch));
        }
        try {
            latch.await();
        }catch (InterruptedException e){
            log.error(e.getMessage());
        }
        ExecutorServiceUtil.shutdown(executorService);
    }
    private void dummyPrase1(int i,CountDownLatch latch){
           dummyParse(i);
           latch.countDown();
       }
    private void loop(){
        for (int i=0;i<LOG_FILE_COUNT;i++){
            dummyParse(i);
        }
    }
    private void dummyParse(int i){
        try{
            val r=rnd(10,50);
            if (log.isDebugEnabled()) log.debug("{} => sleep {} ms",i,r);
            Thread.sleep(r);
        }catch (InterruptedException e){
            log.error(e.getMessage());
        }
    }
    private int rnd(int min,int max){
        return  random.nextInt(max-min+1)+min;
    }
    private final int LOG_FILE_COUNT=256;
    private  final Random random=new Random(System.currentTimeMillis());
}
